/*
 * @Author: 灰灰
 * @Date: 2022-01-07 10:02:38
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-01-09 20:05:26
 * @Description: 导出文件，比如 img， pdf，excel等
 */

import {
  saveAs
} from "file-saver";
import XLSX from 'xlsx';
import checkFormat from "./util/checkFormat";
import html2canvas from "html2canvas";
import {
  Loading
} from 'element-ui'

let loading = null;

// 显示加载loading
export function showLoading(title) {
  loading = Loading.service({
    lock: true,
    text: title || 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
}

export function closeLoading() {
  loading.close();
  loading = null;
}

/**
 * 将el-table的表格 可以多个sheet 导出 excel
 * @param {Array} sheetList sheet数组，可以是selectorId，或者对象{selectorId: 'divId', name: 'sheet名称'}
 * @param {String} name excel名称
 * @param {Function} callback 回调
 */
export function exportTableToExcel(sheetList, name = 'test', callback) {
  showLoading('excel生成中...');
  setTimeout(() => {
    const workbook = XLSX.utils.book_new();
    // 多个sheet需要导到excel
    sheetList.forEach(item => {
      let selectorId = item;
      let sheetName;
      if (checkFormat.isObject(item)) {
        // 如果是对象，就会有 sheet名称
        selectorId = item.selectorId;
        sheetName = item.name;
      }
      let ws;
      // 获取 selectorId 的节点
      let selector = document.querySelector(selectorId);
      // 看有没有 fixed 节点
      const fixNode = selector.querySelector('.el-table__fixed');
      // 生成 sheet 页
      const sheetSelector = (fixNode && selector) ? selector.removeChild(fixNode) : selector;
      fixNode && selector && selector.appendChild(fixNode);
      ws = XLSX.utils.table_to_sheet(sheetSelector);
      // xlsx 追加 sheet 
      XLSX.utils.book_append_sheet(workbook, ws, sheetName);
    })

    const wbOut = XLSX.write(workbook, {
      bookType: 'xlsx',
      bookSST: true,
      type: 'array'
    });

    try {
      //生成 Blob 对象表示一个不可变、原始数据的类文件对象
      const blob = new Blob([wbOut], {
        type: 'application/octet-stream'
      });
      saveAs(blob, `${name}.xlsx`);
      closeLoading();
      callback && callback();
    } catch (e) {
      if (typeof console !== 'undefined') console.log('exportTableToExcel error:', e, wbOut)
    }
  }, 500);
}

/**
 * 导出图片
 * @param {String} selectorId 选择器id
 * @param {String} name 图片名称
 * @param {Function} callback 导出图片成功回调
 */
export function exportImg(selectorId, name = "test", callback) {
  showLoading('图片生成中...');
  setTimeout(() => {
    exportImgWithWidth(selectorId, name, '', () => {
      closeLoading();
      callback && callback()
    })
  }, 1000);
}

// 导出图片，可以设置宽度
export function exportImgWithWidth(selectorId, name = "test", width, callback) {
  // 获取当前选择器id的节点
  const targetDom = document.querySelector(selectorId);
  // 将当前节点克隆一份
  const copyDom = targetDom.cloneNode(true);
  copyDom.style.width = (width || targetDom.offsetWidth) + 'px';
  copyDom.style.height = targetDom.offsetHeight + 'px';
  // 将克隆的节点追加到当前节点上
  targetDom.appendChild(copyDom);
  const options = {
    useCORS: true,
    backgroundColor: 'white'
  };

  html2canvas(copyDom, options).then(canvas => {
    const imgUrl = canvas.toDataURL('image/png');
    // 创建a标签进行下载
    const link = document.createElement('a');
    link.href = imgUrl; // 图片地址
    link.download = name;
    document.body.appendChild(link);
    link.click();

    // 移除追加元素
    document.body.removeChild(link);
    targetDom.removeChild(copyDom);

    callback && callback()
  })

}